package logic

import (
	"context"
	"gozerogateway/rpc/model/svcmodel"

	"encoding/json"
	"github.com/zeromicro/go-zero/core/logx"
	"gozerogateway/rpc/svc/internal/svc"
)

type ServiceDetailLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewServiceDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ServiceDetailLogic {
	return &ServiceDetailLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

type ServiceDetailDo struct {
	Info *svcmodel.GatewayServiceInfo `json:"info"` //base info

	HTTPRule      *svcmodel.GatewayServiceHttpRule      `json:"http_rule"` //rule
	TCPRule       *svcmodel.GatewayServiceTcpRule       `json:"tcp_rule"`
	GRPCRule      *svcmodel.GatewayServiceGrpcRule      `json:"grpc_rule"`
	LoadBalance   *svcmodel.GatewayServiceLoadBalance   `json:"load_balance"`
	AccessControl *svcmodel.GatewayServiceAccessControl `json:"access_control"`
}

// *svcclient.ServiceDetailResp
//l *ServiceDetailLogic
func (l *ServiceListLogic) ServiceDetail(in *svcmodel.GatewayServiceInfo) (*ServiceDetailDo, error) {
	// todo: add your logic here and delete this line

	ServiceId := in.Id
	httpDo, err := l.svcCtx.SvcHttpModel.FindOne(l.ctx, ServiceId)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("根据service_id查询http表信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}

	tcpDo, err := l.svcCtx.SvcTcpModel.FindOne(l.ctx, ServiceId)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("根据service_id查询tcp表信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}

	grpcDo, err := l.svcCtx.SvcGrpcModel.FindOne(l.ctx, ServiceId)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("根据service_id查询grpc表信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}

	accessControlDo, err := l.svcCtx.SvcAccessControlModel.FindOne(l.ctx, ServiceId)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("根据service_id查询accesscontrol表信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}

	loadBalanceDo, err := l.svcCtx.SvcLoadBalanceModel.FindOne(l.ctx, ServiceId)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("根据service_id查询loadbalance表信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}
	detail := &ServiceDetailDo{
		Info:          in,
		HTTPRule:      httpDo,
		TCPRule:       tcpDo,
		GRPCRule:      grpcDo,
		AccessControl: accessControlDo,
		LoadBalance:   loadBalanceDo,
	}
	return detail, nil
	//return &svcclient.ServiceDetailResp{}, nil
}
